<?php
/*******************************************
* Thank-o-matic
* Re-edited by Adk-Team
* www.smfpersonal.net
* 2009-2011
*******************************************/

if (!defined('SMF'))
	die('Hacking attempt...');
	
// This function passes control through to the relevant tab.
function ManageThankYouPost()
{
	global $context, $txt, $scripturl, $modSettings, $settings, $sourcedir;

	// You need to be an admin to edit settings!
	isAllowedTo('admin_forum');

	loadLanguage('Help');
	loadLanguage('ManageSettings');

	$context['page_title'] = $txt['thankyouposttitle'];

	// Will need the utility functions from here.
	require_once($sourcedir . '/ManageServer.php');

	// This is the standard Template sometimes i need a diffrent one :P
	$context['sub_template'] = 'show_settings';

	$subActions = array(
		'general' => 'ManageThankYouPostGeneral',
		'layout' => 'ManageThankYouPostLayout',
		'permission' => 'ManageThankYouPostPermission',
		'boards' => 'ManageThankYouPostBoards',
		'modrelated' => 'ManageThankYouPostModifcations',
	);

	// Load up all the tabs...
	$context[$context['admin_menu_name']]['tab_data'] = array(
		'title' => &$txt['thankyouposttitle'],
		'tabs' => array(
			'general' => array(
				'label' => $txt['general_settings'],
				'description' => $txt['thx_gernalSettingsDesc'],
			),
			'layout' => array(
				'label' => $txt['mods_cat_layout'],
				'description' => $txt['thx_layoutSettingsDesc'],
			),
			'permission' => array(
				'label' => $txt['edit_permissions'],
				'description' => $txt['thx_permissionSettingsDesc'],
			),
			'boards' => array(
				'label' => $txt['admin_boards'],
				'description' => $txt['thx_boradSettingsDesc'],
			),
			'modrelated' => array(
				'label' => $txt['thxmodification'],
				'description' => $txt['thx_modifciationSettingsDesc'],
			),
		),
	);

	// Call the right function for this sub-acton.
	if(!empty($_REQUEST['sa']) && !empty($subActions[$_REQUEST['sa']]))
		$subActions[$_REQUEST['sa']]();
	else
		$subActions['general']();
}

function ManageThankYouPostGeneral($return_config = false)
{
	global $txt, $scripturl, $context, $settings, $sc, $modSettings;

	$config_vars = array(
			// Thank You Post, some Stanadard settings :)
			array('select', 'thankYouPostType', explode('|', $txt['thankYouPostTypeSelect'])),
			array('check', 'thankYouPostColors'),
			array('int', 'thankYouPostSpamProtection', 'postinput' => '<span class="smalltext"><em>' . $txt['thankYouPostSpamProtectionPostInput'] . '</em></span>'),
		'',
			// Okay only the preview settings :)
			array('check', 'thankYouPostPreview'),
			array('int', 'thankYouPostPreviewHM', 'postinput' => '<span class="smalltext"><em>' . $txt['thankYouPostPreviewHMPostInput'] . '</em></span>'),
			array('select', 'thankYouPostPreviewOrder', explode('|', $txt['thankYouPostPreviewOrderSelect'])),
		'',
			// Okay only the Full List settings :)
			array('select', 'thankYouPostFullOrder', explode('|', $txt['thankYouPostFullOrderSelect'])),
		'',
			// Some Addon that can be outputed
			array('check', 'thankYouPostDisplayPage'),
			array('check', 'thankYouPostStatsEnabled'),
			array('check', 'thankYouPostMemberList'),
	);

	// Karma need some check before i add it ;)
	if (in_array('k', $context['admin_features']))
	{
		$config_vars[] = '';
		$config_vars[] = array('check', 'thankYouPostIncraseKarmaGood');
	}
	// Moderation logging?
	if (!empty($modSettings['modlog_enabled']))
	{
		$config_vars[] = '';
		$config_vars[] = array('check', 'thankYouPostModerationLog');
	}

	if ($return_config)
		return $config_vars;

	// Convert the modSettings to the new one (make it compatible)
	if(!isset($modSettings['thankYouPostType']) && !isset($_POST['thankYouPostType']))
		$modSettings['thankYouPostType'] = (empty($modSettings['thankYouPostOnePerPost']) ? (!empty($modSettings['thankYouPostFirstPostOnly']) ? 2 : 0) : 1);

	// Saving?
	if (isset($_GET['save']))
	{
		// The fist option need to be made compatible
		if (empty($_POST['thankYouPostType']))
			updateSettings(array('thankYouPostOnePerPost' => 0, 'thankYouPostFirstPostOnly' => 0));
		else
			updateSettings(array('thankYouPostOnePerPost' => ($_POST['thankYouPostType'] == 1 ? 1 : 0), 'thankYouPostFirstPostOnly' => ($_POST['thankYouPostType'] == 2 ? 1 : 0)));

		saveDBSettings($config_vars);
		redirectexit('action=admin;area=thankyoupostsettings;');
	}

	$context['post_url'] = $scripturl . '?action=admin;area=thankyoupostsettings;save';
	$context['settings_title'] = $txt['thankyouposttitle'];

	prepareDBSettingContext($config_vars);
}

function ManageThankYouPostLayout($return_config = false)
{
	global $txt, $scripturl, $context, $settings, $sc, $modSettings;

	$config_vars = array(
			// Show the Thank You Post Informations on the Display Page
			array('check', 'thankYouPostDisplayDisableBecame'),
			array('check', 'thankYouPostDisplayDisableMade'),
		'',
			array('check', 'thankYouPostMemberListDisableBecame'),
			array('int', 'thankYouPostMemberListSizeBecame', 'size' => 7, 'postinput' => '<span class="smalltext"><em>' . $txt['thankYouPostMemberListStandardSize'] . '</em></span>'),
			array('check', 'thankYouPostMemberListDisableMade'),
			array('int', 'thankYouPostMemberListSizeMade', 'size' => 7, 'postinput' => '<span class="smalltext"><em>' . $txt['thankYouPostMemberListStandardSize'] . '</em></span>'),
		'',
			// Okay only the preview settings :)
			array('select', 'thankYouPostCounterOutput', explode('|', $txt['thankYouPostCounterOutputSelect'])),
			array('select', 'thankYouPostStartOutput', explode('|', $txt['thankYouPostStartOutputSelect'])),
			array('text', 'thankYouPostStartOutputText'),
		'',
			// Ajax Thank You Setup
			array('check', 'thankYouPostAJAX'),
			array('check', 'thankYouPostAJAXModButtonsDisable', 'disabled' => empty($modSettings['thankYouPostAJAX'])),
	);

	if ($return_config)
		return $config_vars;

	// Saving?
	if (isset($_GET['save']))
	{
		saveDBSettings($config_vars);
		redirectexit('action=admin;area=thankyoupostsettings;sa=layout');
	}

	$context['post_url'] = $scripturl . '?action=admin;area=thankyoupostsettings;sa=layout;save';
	$context['settings_title'] = $txt['thankyouposttitle'];

	prepareDBSettingContext($config_vars);
}

// This is only for the Board default inline permission!
function ManageThankYouPostPermission($return_config = false)
{
	global $txt, $scripturl, $context, $settings, $sc, $sourcedir;
	global $modSettings, $smcFunc;

	// Yes i will use the same system, but i use a special template extension :P
	$config_vars = array(
			array('permissions', 'thank_you_post_show'),
			array('permissions', 'thank_you_post_post'),
	);

	if ($return_config)
		return $config_vars;

	// Before prepare the context :D
	prepareDBSettingContext($config_vars);

	// Follow Permission should be outputed, easy to extent ;P
	$context['board_permissions'] = array(
			'thank_you_post_show',
			'thank_you_post_post',
	);

	// Saving?
	if (isset($_GET['save']))
	{
		// Okay Seperate the board permission from the normal permissions, i will handle it seperate :D
		loadIllegalPermissions();
		$insertRows = array();
		foreach ($context['board_permissions'] as $permission)
		{
			if (!isset($_POST[$permission]))
				continue;

			foreach ($_POST[$permission] as $id_group => $value)
			{
				if (in_array($value, array('on', 'deny')) && (empty($context['illegal_permissions']) || !in_array($permission, $context['illegal_permissions'])))
					$insertRows[] = array((int) $id_group, 1, $permission, $value == 'on' ? 1 : 0);
			}

			// This value never exists :P i mean this will not stored in the normal way :)
			unset($_POST[$permission]);
		}

		// Remove the old permissions...
		$smcFunc['db_query']('', '
			DELETE FROM {db_prefix}board_permissions
			WHERE permission IN ({array_string:permissions})
				AND id_profile = {int:id_profile_default}
			' . (empty($context['illegal_permissions']) ? '' : ' AND permission NOT IN ({array_string:illegal_permissions})'),
			array(
				'id_profile_default' => 1,
				'illegal_permissions' => !empty($context['illegal_permissions']) ? $context['illegal_permissions'] : array(),
				'permissions' => $context['board_permissions'],
			)
		);

		// ...and replace them with new ones.
		if (!empty($insertRows))
			$smcFunc['db_insert']('insert',
				'{db_prefix}board_permissions',
				array('id_group' => 'int', 'id_profile' => 'int', 'permission' => 'string', 'add_deny' => 'int'),
				$insertRows,
				array('id_group', 'permission')
			);

		// Do a full child update.
		updateChildPermissions(array(), -1);

		// Just in case we cached this.
		updateSettings(array('settings_updated' => time()));

		saveDBSettings($config_vars);
		redirectexit('action=admin;area=thankyoupostsettings;sa=permission');
	}

	// Overwrite the board permissions with the correct ones...
	loadLanguage('ManagePermissions');

	// Have some nice helper :D
	require_once($sourcedir . '/ManagePermissions.php');

	// Setup standard permissions groups
	// $context = array();
	foreach ($context['board_permissions'] as $permission)
		$context[$permission] = array(
			-1 => array(
				'id' => -1,
				'name' => $txt['membergroups_guests'],
				'is_postgroup' => false,
				'status' => 'off',
			),
			0 => array(
				'id' => 0,
				'name' => $txt['membergroups_members'],
				'is_postgroup' => false,
				'status' => 'off',
			),
		);

	$request = $smcFunc['db_query']('', '
		SELECT id_group, CASE WHEN add_deny = {int:denied} THEN {string:deny} ELSE {string:on} END AS status, permission
		FROM {db_prefix}board_permissions
		WHERE id_group IN (-1, 0)
			AND permission IN ({array_string:permissions})
			AND id_profile = {int:id_profile_default}',
		array(
			'id_profile_default' => 1,
			'denied' => 0,
			'permissions' => $context['board_permissions'],
			'deny' => 'deny',
			'on' => 'on',
		)
	);
	while ($row = $smcFunc['db_fetch_assoc']($request))
		$context[$row['permission']][$row['id_group']]['status'] = $row['status'];
	$smcFunc['db_free_result']($request);

	$request = $smcFunc['db_query']('', '
		SELECT mg.id_group, mg.group_name, mg.min_posts, IFNULL(p.add_deny, -1) AS status, p.permission
		FROM {db_prefix}membergroups AS mg
			LEFT JOIN {db_prefix}board_permissions AS p ON (p.id_group = mg.id_group AND p.permission IN ({array_string:permissions}))
		WHERE mg.id_group NOT IN (1, 3)
			AND mg.id_parent = {int:not_inherited}' . (empty($modSettings['permission_enable_postgroups']) ? '
			AND mg.min_posts = {int:min_posts}' : '') . '
		ORDER BY mg.min_posts, CASE WHEN mg.id_group < {int:newbie_group} THEN mg.id_group ELSE 4 END, mg.group_name',
		array(
			'id_profile_default' => 1,
			'not_inherited' => -2,
			'min_posts' => -1,
			'newbie_group' => 4,
			'permissions' => $context['board_permissions'],
		)
	);
	while ($row = $smcFunc['db_fetch_assoc']($request))
	{
		// Initialize each permission as being 'off' until proven otherwise.
		foreach ($context['board_permissions'] as $permission)
			if (!isset($context[$permission][$row['id_group']]))
				$context[$permission][$row['id_group']] = array(
					'id' => $row['id_group'],
					'name' => $row['group_name'],
					'is_postgroup' => $row['min_posts'] != -1,
					'status' => 'off',
				);

		if(!empty($row['permission']))
			$context[$row['permission']][$row['id_group']]['status'] = empty($row['status']) ? 'deny' : ($row['status'] == 1 ? 'on' : 'off');
	}
	$smcFunc['db_free_result']($request);

	// Okay remove the not allowed Guest permissions :D
	loadIllegalGuestPermissions();
	foreach($context['non_guest_permissions'] as $permission)
		if (!empty($context[$permission]))
			unset($context[$permission][-1]);

	// Some last important Settings :)
	$context['post_url'] = $scripturl . '?action=admin;area=thankyoupostsettings;sa=permission;save';
	$context['settings_title'] = $txt['thankyouposttitle'];
}

function ManageThankYouPostBoards($return_config = false)
{
	global $context, $txt, $settings, $user_info, $modSettings, $smcFunc, $scripturl;

	// Saving?
	if (isset($_GET['save']))
	{
		// Check the Sessions :)
		checkSession('post');

		//First disable all
		$smcFunc['db_query']('', '
			UPDATE {db_prefix}boards
				SET thank_you_post_enable = {int:thank_you_post_enabled}',
			array(
				'thank_you_post_enabled' => 1
			)
		);

		//Nothing to do?
		if(!empty($_POST['brd']))
		{
			//No Double Entries ;)
			$_POST['brd'] = array_unique($_POST['brd']);

			// Enable it for some boards
			$smcFunc['db_query']('', '
				UPDATE {db_prefix}boards
					SET thank_you_post_enable = {int:thank_you_post_enabled}
				WHERE id_board IN ({array_int:boards})',
				array(
					'thank_you_post_enabled' => 0,
					'boards' => $_POST['brd']
				)
			);
		}

		//Redirect ;)
		redirectexit('action=admin;area=thankyoupostsettings;sa=boards');
	}

	// Fist Load the list where he/she/it is a Moderator ;)
	$request = $smcFunc['db_query']('', '
		SELECT id_board
		FROM {db_prefix}boards
		WHERE thank_you_post_enable != {int:thank_you_post_enabled}',
		array(
			'thank_you_post_enabled' => 1
		)
	);

	$collectThankYouBoards = array();
	while($row = $smcFunc['db_fetch_assoc']($request))
		$collectThankYouBoards[$row['id_board']] = $row['id_board'];

	// Find all the boards this user is allowed to see.
	$request = $smcFunc['db_query']('', "
		SELECT b.id_cat, c.name AS cat_name, b.id_board, b.name, b.child_level
		FROM {db_prefix}boards AS b
			LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
		WHERE {query_see_board}");
	$context['num_boards'] = $smcFunc['db_num_rows']($request);
	$context['categories'] = array();
	while ($row = $smcFunc['db_fetch_assoc']($request))
	{
		// This category hasn't been set up yet..
		if (!isset($context['categories'][$row['id_cat']]))
			$context['categories'][$row['id_cat']] = array(
				'id' => $row['id_cat'],
				'name' => $row['cat_name'],
				'boards' => array()
			);

		// Set this board up, and let the template know when it's a child.  (indent them..)
		$context['categories'][$row['id_cat']]['boards'][$row['id_board']] = array(
			'id' => $row['id_board'],
			'name' => $row['name'],
			'is_moderator' => isset($collectThankYouBoards[$row['id_board']]),
			'child_level' => $row['child_level'],
		);
	}
	mysql_free_result($request);

	// Now, let's sort the list of categories into the boards for templates that like that.
	$temp_boards = array();
	foreach ($context['categories'] as $category)
	{
		$temp_boards[] = array(
			'name' => $category['name'],
			'child_ids' => array_keys($category['boards'])
		);
		$temp_boards = array_merge($temp_boards, array_values($category['boards']));
	}

	$max_boards = ceil(count($temp_boards) / 2);
	if ($max_boards == 1)
		$max_boards = 2;

	// Now, alternate them so they can be shown left and right ;).
	$context['board_columns'] = array();
	for ($i = 0; $i < $max_boards; $i++)
	{
		$context['board_columns'][] = $temp_boards[$i];
		if (isset($temp_boards[$i + $max_boards]))
			$context['board_columns'][] = $temp_boards[$i + $max_boards];
		else
			$context['board_columns'][] = array();
	}

	$context['all_checked'] = $context['num_boards'] == count($collectThankYouBoards);

	$context['post_url'] = $scripturl . '?action=admin;area=thankyoupostsettings;sa=boards;save';
	$context['settings_title'] = $txt['thankyouposttitle'];

	// Load a diffrent Template
	loadTemplate('ThankYouPost');
	$context['sub_template'] = 'thank_you_show_boards';
}

function ManageThankYouPostModifcations($return_config = false)
{
	global $txt, $scripturl, $context, $settings, $sc;

	$config_vars = array(
			// Hmm it'S compatible to my Hide Mod... and have three options xD
			array('check', 'thankYouPostUnhidePost'),
			array('check', 'thankYouPostThxUnhideAll'),
			array('check', 'thankYouPostDisableUnhide'),
	);

	if ($return_config)
		return $config_vars;

	// Saving?
	if (isset($_GET['save']))
	{
		// Fix some not possible checks :)
		if (!empty($_POST['thankYouPostOnePerPost']))
			unset($_POST['thankYouPostFirstPostOnly']);
		if (!empty($_POST['thankYouPostThxUnhideAll']))
			unset($_POST['thankYouPostUnhidePost']);
		saveDBSettings($config_vars);
		redirectexit('action=admin;area=thankyoupostsettings;sa=modrelated');
	}

	$context['post_url'] = $scripturl . '?action=admin;area=thankyoupostsettings;sa=modrelated;save';
	$context['settings_title'] = $txt['thankyouposttitle'];

	prepareDBSettingContext($config_vars);
}


?>